package screen;

import java.util.Vector;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import animation.FlyText;

import main.GameCanvas;
import main.NuoiThuMidlet;
import model.Command;
import model.IAction;
import model.PlayerInfo;
import model.Position;
import service.GlobalService;
import utilities.CRes;
import utilities.GameResource;
import utilities.TileMap;
import font.BitmapFont;

public class BauCuaScr extends PlayGameScr{
	static BauCuaScr instance;
	private int m_iTime;
	private int m_iTimeLac;
	int m_deltaX;
	int m_deltaY;
	int deltaArrowY = 2;

	byte m_iCountNumDatCuoc;
	byte m_iCurrentNum;
	
	int m_iSelectedRow;
	int m_iSelectedCol;
	int m_iMyPos;
	int m_iDeltaShowDice;
	
	boolean m_bIsLacBauCua;
	boolean m_bIsSelected = false;
	boolean m_bIsShowDice = false;
	boolean m_bIsShowResult = false;
	boolean m_bIsFinish = false;
	boolean m_bIIsClock = true;
	boolean m_bContinue = false;
	
	Command m_lacBauCuaCmd;
	Command m_datCuocCmd;
	Command m_finishCmd;
	Command m_continueCmd;
	Command m_openDiceCmd;
	
	boolean m_bIsJoinGame = false;
	
	byte[] m_arrResult;
	short[] m_arrPosXDice;
	short[] m_arrPosYDice;

	byte[][] m_arrPlayerData;
			
    public static BauCuaScr gI() {
        if (instance == null) {
            instance = new BauCuaScr(4);
        }
        return instance;
    }
    
    public static void clean(){
		if(instance != null){
			instance.m_arrResult = null;
			instance.m_arrPosXDice = null;
			instance.m_arrPosYDice = null;
			instance.m_arrPlayerData = null;
			instance.m_imgBackground = null;
			instance.m_arrChatContent = null;
			instance.m_arrPlayers = null;
			instance.m_arrPos = null;
		}
		instance = null;		
	}
    
	public BauCuaScr(int maxPlayer) {
		super(maxPlayer);
		// TODO Auto-generated constructor stub
		TileMap.instance.loadMap(TileMap.QUEST_PET_MAP);
		
		m_bIsDisplayAnimal = false;
		
		m_arrPos[0] = new Position(10, GameCanvas.h - 200);
		m_arrPos[0].anchor = 0;
		
		m_arrPos[1] = new Position(GameCanvas.w - 70, m_arrPos[0].y);
		m_arrPos[1].anchor = 1;
		
		m_arrPos[2] = new Position(m_arrPos[1].x, GameCanvas.h - 100);
		m_arrPos[2].anchor = 1;
		
		m_arrPos[3] = new Position(m_arrPos[0].x, m_arrPos[2].y);
		m_arrPos[3].anchor = 0;
		
		m_arrResult = new byte[3];//mang ket qua cua xuc xac
		m_arrPosXDice = new short[3];//mang vi tri cua xuc xac
		m_arrPosYDice = new short[3];//mang vi tri cua xuc xac
		
		m_arrPlayerData = new byte[4][6];//mang dat cuoc cua cac ban choi cung
		
		m_lacBauCuaCmd = new Command("Lắc", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				GlobalService.gI().doLacBauCua(m_iRoomID, m_iBoardID);
				
				m_cmdCenter = null;
			}
		});
		
		m_datCuocCmd = new Command("Đặt", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				int index = m_iSelectedRow * 3 + m_iSelectedCol;
				if(m_bIsSelected){
					
					if(m_iCountNumDatCuoc + m_iCurrentNum <= 3){
						m_bIsSelected = false;
						
						m_iCountNumDatCuoc = (byte)(m_iCountNumDatCuoc + m_iCurrentNum);
						
						m_arrPlayerData[m_iMyPos][index] = m_iCurrentNum;
						
						m_cmdRight = m_finishCmd;
					}
					else{
						GameCanvas.startOK("Bạn chỉ được đặt tối đa 3 đơn vị", new IAction() {
							
							public void perform() {
								// TODO Auto-generated method stub
								m_bIsSelected = false;
								m_cmdRight = m_finishCmd;
								
								GameCanvas.endDlg();
							}
						});
					}
				}
				else
				{					
					if(m_arrPlayerData[m_iMyPos][index] == 0 && m_iCountNumDatCuoc == 3){
						GameCanvas.startOKDlg("Bạn chỉ được đặt tối đa 3 đơn vị");
						return;
					}
					
					m_iCurrentNum = m_arrPlayerData[m_iMyPos][index];
					if(m_iCurrentNum == 0){
						m_iCurrentNum = 1;
					}
					
					m_iCountNumDatCuoc -= m_arrPlayerData[m_iMyPos][index];
					
					if(NuoiThuMidlet.m_myPlayerInfo.m_iId != m_iOwnerID){
						m_bIsSelected = true;
					}
					m_cmdRight = null;
				}
			}
		});
		
		m_finishCmd = new Command("Xong", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				GlobalService.gI().doSubmitData(m_iRoomID, m_iBoardID, m_arrPlayerData[m_iMyPos]);
				
				m_bIsFinish = true;
				m_cmdCenter = null;
				m_cmdRight = null;
			}
		});
		
		m_continueCmd = new Command("Tiếp tục", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				continueNewGame();
			}
		});
		
		m_openDiceCmd = new Command("Mở", new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				GlobalService.gI().doMoToBauCua(m_iRoomID, m_iBoardID);
				
				m_cmdCenter = null;
			}
		});
	}

	public void switchToMe(byte roomID1, byte boardID, Vector vtPlayers,
			int ownerID, int money) {
		// TODO Auto-generated method stub
		super.switchToMe(roomID1, boardID, vtPlayers, ownerID, money);
		
		m_iMyPos = findPlayerPos(NuoiThuMidlet.m_myPlayerInfo.m_iId);
	}

	public void onStartGame(short interval) {
		// TODO Auto-generated method stub
		GameCanvas.endDlg();
		
		startGame();
		
		m_left = GameCanvas.hw - 80;
		m_top = GameCanvas.hh - 102;
		
		m_deltaX = 0;
		m_deltaY = 0;
		m_iCountNumDatCuoc = 0;
		m_iCurrentNum = 0;
		m_iDeltaShowDice = 0;
		m_iTime = interval;
								
		m_bIsSelected = false;
		m_bIsShowDice = false;
		m_bIsShowResult = false;
		m_bIsFinish = false;
		m_bIIsClock = true;
		m_bContinue = false;
		m_bIsJoinGame = true;
		//reset data
		int i, j;
		
		for(i = 0; i < 6; i++){
			//m_arrDatCuoc[i] = 0;
			for(j = 0; j < 4; j++){
				m_arrPlayerData[j][i] = 0;
			}
		}
		for(i = 0; i < m_arrPosXDice.length; i++){
			m_arrPosXDice[i] = (short)(m_left + 80);
			m_arrPosYDice[i] = (short)(m_top + 160);
		}
		
		m_cmdCenter = null;
		if(m_iOwnerID == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			m_cmdCenter = m_lacBauCuaCmd;
		}
	}
	
	public void continueNewGame(){
		stopGame();		
		GameCanvas.endDlg();
	
		m_bIsShowDice = false;
	}
	
	private int m_itick = 0;
	public void paint(Graphics g){
		g.translate(-g.getTranslateX(), -g.getTranslateY());
		g.setClip(0, 0, GameCanvas.w, GameCanvas.h);
		
		TileMap.instance.paintMap(g, 0, 0);	
		
		if(isPlaying()){
			PaintPopup.paintBox(g, m_left, m_top, 160, 204, 2, 0xfcedc4, 0xf24c4c);
			
			//paint ban co
			int i;
			for(i = 0; i < 3; i++)
				PaintPopup.paintCellBauCua(g, m_left + 10 + 50 * i, m_top + 20, 40, 40, 0xf9a235, 0xfafebe);
				
			for(i = 0; i < 3; i++)
				PaintPopup.paintCellBauCua(g, m_left + 10 + 50 * i, m_top + 70, 40, 40, 0x5ea0f1, 0xdfecfd);
			
			
			if(m_bIsShowResult){
				m_itick++;
				g.setColor(0x0000ff);
				if(m_itick > 2){
					m_itick = 0;
					g.setColor(0x00ff00);
				}
				for(i = 0; i < 6; i++)					
					if(i == m_arrResult[0] || i == m_arrResult[1] || i == m_arrResult[2]){
						int tmpX = m_left + 10 + 50 * (i%3);
						int tmpY = m_top + 20 + 50 * (i/3);
						g.drawRect(tmpX, tmpY, 40, 40);
						g.drawRect(tmpX+1, tmpY+1, 38, 38);
					}
			}
			
			//paint selected cell
			
			int tmpX = m_left + 10 + 50 * m_iSelectedCol;
			int tmpY = m_top + 20 + 50 * m_iSelectedRow;
			if(m_iOwnerID != NuoiThuMidlet.m_myPlayerInfo.m_iId && !m_bIsFinish){
				PaintPopup.paintCellBauCua(g, tmpX, tmpY, 40, 40, 0xff0000, 0xffffff);
			}
			
			Image img = GameResource.instance.imgDice;
			g.drawRegion(img, 91, 23, 22, 26, 0, m_left + 18, m_top + 27, 20);
			g.drawRegion(img, 65, 0, 23, 23, 0, m_left + 68, m_top + 30, 20);
			g.drawRegion(img, 115, 0, 26, 24, 0, m_left + 117, m_top + 30, 20);
			g.drawRegion(img, 113, 24, 27, 16, 0, m_left + 17, m_top + 82, 20);
			g.drawRegion(img, 87, 0, 27, 23, 0, m_left + 66, m_top + 80, 20);
			g.drawRegion(img, 67, 23, 24, 26, 0, m_left + 117, m_top + 77, 20);
						
			//paint money dat cuoc
			int j;
			for(i = 0; i < 4; i++){
				for(j = 0; j < 6; j++){
					if(m_arrPlayerData[i][j] != 0){
						tmpX = m_left + 10 + 50 * (j % 3);
						tmpY = m_top + 20 + 50 * (j / 3);
						
						PaintPopup.paintMoneyBauCua(g, i%3, tmpX + ((i % 2 == 0)? 0: 25), tmpY + ((i / 2 == 0)? 0: 25));
						if(i == 2){
							tmpX += 7;
						}
						BitmapFont.drawOutlinedString(g, "" + m_arrPlayerData[i][j], tmpX + ((i % 2 == 0)? 0: 30), tmpY + ((i / 2 == 0)? 0: 25), 0xffff00, 0x000000, Graphics.LEFT);
					}
				}
			}
			
			if(m_bIsSelected){
				tmpX = m_left + 10 + 50 * m_iSelectedCol;
				tmpY = m_top + 20 + 50 * m_iSelectedRow;
				
				PaintPopup.paintArrowVertical(g, 0, tmpX + 10, tmpY, 30, deltaArrowY);
				deltaArrowY = 2 - deltaArrowY;
				
				PaintPopup.paintMoneyBauCua(g, m_iMyPos%3, tmpX + 10, tmpY + 10);
				BitmapFont.drawOutlinedString(g, "" + m_iCurrentNum, tmpX + 30, tmpY + 10, 0x00ff00, 0x000000, Graphics.LEFT);
			}		
			
			PaintPopup.paintBox(g, m_left + 40, m_top + 120, 80, 80, 2, 0xfcedc4, 0xf24c4c);
			
			//paint xuc xac va to
			PaintPopup.paintToBauCua(g, m_left + 47 + m_deltaX, m_top + 127 + m_deltaY, 65, 65, 100, 100);
			for(i = 0; i < 3; i++){
				PaintPopup.paintDiceBauCua(g, m_arrPosXDice[i], m_arrPosYDice[i], m_arrResult[i]);
			}
			PaintPopup.paintToBauCua(g, m_left + 47 + m_deltaX, m_top + 127 + m_deltaY + m_iDeltaShowDice, 65, 65, 100, 100);
			
			//paint player
			for(i = 0; i < m_arrPlayers.length; i++){
				if(m_arrPlayers[i] != null && m_arrPlayers[i].m_iId != -1){
					m_arrPlayers[i].paintAvatarInBoard(g, (i % 2) == 0? 2: GameCanvas.w - 67, (i /2 == 0)? 2 : m_top + 150, 75, 40);
					if(m_arrPlayers[i].m_iId == m_iOwnerID){
						GameResource.instance.m_frameIconItems.drawFrame(21, (i % 2) == 0? 42: GameCanvas.w - 67, (i /2 == 0)? 45 : m_top + 120, 0, g);
					}
					else
					{
						PaintPopup.paintMoneyBauCua(g, i % 3, (i % 2) == 0? 42: GameCanvas.w - 67, (i /2 == 0)? 45 : m_top + 120);
					}
				}
			}
			if(m_bIIsClock){
				PaintPopup.paintBoxClock(g, GameCanvas.hw-10, 10, ""+m_iTime);
			}
			
		}
		
		
		
		super.paint(g);
	}
	
	public void update(){
		if(isPlaying()){
    		m_iCurrentTime++;
    		
    		if(m_iCurrentTime % 20 == 0 && m_iTime > 0)
    			m_iTime--;
    		
    		
    		if(m_iTime <=0 && m_bContinue){
    			m_bIIsClock = false;
    			m_bContinue = false;
    			continueNewGame();
    		}
    		
    	
    		if(m_bIsLacBauCua){
    			m_deltaX = CRes.random(-3, 3);
    			m_deltaY = CRes.random(-3, 3);
    			
    			m_iTimeLac++;
    			if(m_iTimeLac > 50){
    				m_bIsLacBauCua = false;
    				m_iTimeLac = 0;
    				
    				m_cmdCenter = null;
    				m_bIIsClock = false;
    				
    				if(m_iOwnerID != NuoiThuMidlet.m_myPlayerInfo.m_iId){
    					m_cmdCenter = m_datCuocCmd;
    					
    				}
    			}
    		}
    		else
    		{
    			m_deltaX = 0;
    			m_deltaY = 0;
    			
    			if(m_bIsShowDice){
    				if(m_iDeltaShowDice < 60){
    					m_iDeltaShowDice += 2;		
    				}
    				else
    				{
    					m_cmdCenter = m_continueCmd;
    					m_bIsShowDice = false;
    					m_bContinue = true;
    					m_bIIsClock = true;
    					m_iTime = 10;
    				}
    			}
    			
    		}
    		
		}
		
		super.update();
	}
	
	public void updateKey(){
    	if(isPlaying()){
    		if (GameCanvas.isPointerClick) {   
        	}
    	
        	if (GameCanvas.keyPressed[8]) {
        		if(m_bIsSelected){
        			m_iCurrentNum++;
        			if(m_iCurrentNum > 3 - m_iCountNumDatCuoc){
        				m_iCurrentNum = 0;
        			}
        		}
        		else
        		{
        			m_iSelectedRow++;
            		if(m_iSelectedRow >= 2)
            			m_iSelectedRow = 0;	
        		}
        		GameCanvas.keyPressed[8] = false;

        	} else if (GameCanvas.keyPressed[2]) {
        		if(m_bIsSelected){
        			m_iCurrentNum--;
        			if(m_iCurrentNum < 0){
        				m_iCurrentNum = (byte)(3 - m_iCountNumDatCuoc);
        			}
        		}
        		else
        		{
        			m_iSelectedRow--;
            		if(m_iSelectedRow < 0)
            			m_iSelectedRow = 1;       		
            	}
        		
        		GameCanvas.keyPressed[2] = false;

        	} else if (GameCanvas.keyPressed[4]) {
        		if(!m_bIsSelected){
        			m_iSelectedCol--;
            		if(m_iSelectedCol < 0)
            			m_iSelectedCol = 2;
            	}
        		GameCanvas.keyPressed[4] = false;

        	} else if (GameCanvas.keyPressed[6]) {
        		if(!m_bIsSelected){
        			m_iSelectedCol++;
            		if(m_iSelectedCol >= 3)
            			m_iSelectedCol = 0;
            	}
        		GameCanvas.keyPressed[6] = false;
        	}
		}
    	
        super.updateKey();
    }
		
	public void onEndGame(boolean isBreak, byte dice1, byte dice2, byte dice3, String des) {
		// TODO Auto-generated method stub
		int i;
		m_arrPosXDice[0] = (short)CRes.random(m_left + 60, m_left + 75);
		m_arrPosYDice[0] = (short)CRes.random(m_top + 140, m_top + 155);
		
		m_arrPosXDice[1] = (short)CRes.random(m_left + 85, m_left + 100);
		m_arrPosYDice[1] = (short)CRes.random(m_top + 140, m_top + 155);
		
		m_arrPosXDice[2] = (short)CRes.random(m_left + 60, m_left + 100);
		m_arrPosYDice[2] = (short)CRes.random(m_top + 165, m_top + 175);
		
		m_arrResult[0] = dice1;
		m_arrResult[1] = dice2;
		m_arrResult[2] = dice3;

		m_bIsShowDice = true;
		m_bIsShowResult = true;
						
		if(m_iMoney > 0 && des.length() > 0){
			GameCanvas.startOK(des, new IAction() {
				
				public void perform() {
					// TODO Auto-generated method stub
					continueNewGame();
					GameCanvas.endDlg();
				}
			}, (byte)1);
		}
		
		for(i = 0; i < m_arrPlayers.length; i++){
			if(m_arrPlayers[i] != null && m_arrPlayers[i].m_iId != m_iOwnerID)
				m_arrPlayers[i].isReady = false;
		}
		
		if(!m_bIsJoinGame || isBreak){
			m_cmdCenter = m_continueCmd;	
			m_bIsShowDice = false;
			m_bIsShowResult = false;
			m_bIsLacBauCua = false;
			m_bIsJoinGame = false;
		}
	}

	public void onLacBauCua() {
		// TODO Auto-generated method stub
		m_cmdCenter = null;
		m_bIsLacBauCua = true;
		m_iTimeLac = 0;
	}
	public void playerLeave(int iDLeave) {
		// TODO Auto-generated method stub
		PlayerInfo p = findPlayer(iDLeave);
		int pos = findPlayerPos(iDLeave);
		if(p != null && pos != -1)
		{
			FlyText text = new FlyText();
			text.startEffect(p.m_UserName + " đã rời sàn" , m_arrPos[pos].x, m_arrPos[pos].y+50, 0xffff00, 0x000000);
		}
		super.playerLeave(iDLeave);
	}
	public void onReceiveBetData(int playerId, byte[] arrFace, byte[] arrData, boolean finish){
		if(finish && m_iOwnerID == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			m_cmdCenter = m_openDiceCmd;
		}
		int pos = findPlayerPos(playerId);
		
		int i;
		for(i = 0; i < arrFace.length; i++){
			if(arrFace[i] != -1)
				m_arrPlayerData[pos][arrFace[i]] = arrData[i];
		}
	}
}
